import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.logging.Logger;

import javax.swing.DefaultListCellRenderer;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JList;
import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.JLabel;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.filechooser.FileFilter;
import javax.swing.JScrollBar;
import java.awt.Font;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class frmMain extends JFrame {

	private JPanel contentPane;
	private JTextField txtTu;
	private JList<Item> list;
	private JLabel lbTu;
	private JLabel lbN;
	private JTextPane lbNghia;
	private ArrayList<Item> dictionary;
	private JMenuItem mntmTiFileT;
	private JMenuItem mntmLuTin;

	public boolean checkWordExist(String tu) {
		for (int i = 0; i < dictionary.size(); i++) {
			if (dictionary.get(i).getTu().equalsIgnoreCase(tu))
				return true;
		}
		return false;
	}

	public boolean addWord(String tu, String nghia) {
		if (checkWordExist(tu))
			return false;
		else {
			dictionary.add(new Item(tu, nghia));
			return true;
		}
	}

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					frmMain frame = new frmMain();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public frmMain() {

		setResizable(false);
		setType(Type.UTILITY);
		createDictionary();

		setTitle("T\u1EEB \u0111i\u1EC3n Vi\u1EC7t Anh");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 597, 412);

		JMenuBar menuBar = new JMenuBar();
		setJMenuBar(menuBar);

		JMenu mnMenu = new JMenu("Menu");
		menuBar.add(mnMenu);

		JMenuItem mntmThmT = new JMenuItem("Th\u00EAm t\u1EEB");
		mntmThmT.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				frmTu frm = new frmTu(frmMain.this, true);
				if (frm.showDialog())
					lbNghia.setText("True");
				else
					lbNghia.setText("false");
			}
		});
		mnMenu.add(mntmThmT);

		JMenuItem mntmThot = new JMenuItem("Tho\u00E1t");
		mntmThot.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				dispose();
			}
		});

		mntmTiFileT = new JMenuItem("Tải file từ điển");
		mntmTiFileT.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JFileChooser chooser = new JFileChooser();
				chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
				chooser.setFileFilter(new FileFilter() {

					@Override
					public String getDescription() {
						// TODO Auto-generated method stub
						return "File (*.dat)";
					}

					@Override
					public boolean accept(File file) {
						if (file.isDirectory()) {
							return true;
						} else {
							String path = file.getAbsolutePath().toLowerCase();
							for (int i = 0, n = 1; i < n; i++) {
								String extension = "dat";
								if ((path.endsWith(extension) && (path
										.charAt(path.length()
												- extension.length() - 1)) == '.')) {
									return true;
								}
							}
						}
						return false;
					}
				});
				if (chooser.showDialog(frmMain.this, "Chọn file") == JFileChooser.APPROVE_OPTION) {
					ObjectInputStream in;
					try {
						in = new ObjectInputStream(new BufferedInputStream(
								new FileInputStream(chooser.getSelectedFile()
										.getAbsolutePath())));
						dictionary = new ArrayList<>();
						dictionary = (ArrayList<Item>) in.readObject();
						in.close();
						loadDictionary();
						System.out.println("Tải từ điển thành công");

					} catch (IOException | ClassNotFoundException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

				}

			}
		});

		mntmLuTin = new JMenuItem("Lưu từ điển vào file");
		mntmLuTin.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				JFileChooser chooser = new JFileChooser();
				chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
				chooser.setAcceptAllFileFilterUsed(false);
				if (chooser.showDialog(frmMain.this, "Chọn nơi lưu file") == JFileChooser.APPROVE_OPTION) {
					File directory = chooser.getSelectedFile();
					String fileName = directory.getPath() + "\\tudien.dat";
					try {
						System.out.println(fileName);
						ObjectOutputStream out = new ObjectOutputStream(
								new BufferedOutputStream(new FileOutputStream(
										fileName)));
						out.writeObject(dictionary);
						out.close();
						JOptionPane optionDialog = new JOptionPane("");
						optionDialog.showMessageDialog(frmMain.this,
								"Đã lưu dữ liệu thành công", "Thành công",
								JOptionPane.INFORMATION_MESSAGE);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						JOptionPane optionDialog = new JOptionPane("");
						optionDialog.showMessageDialog(frmMain.this,
								"Lưu dữ liệu không thành công", "Thất bại",
								JOptionPane.ERROR_MESSAGE);
					}

				}
			}
		});
		mnMenu.add(mntmLuTin);
		mnMenu.add(mntmTiFileT);
		mnMenu.add(mntmThot);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(null);

		JPanel panel = new JPanel();
		panel.setBounds(10, 47, 249, 294);
		contentPane.add(panel);
		panel.setLayout(new BorderLayout(0, 0));

		list = new JList<Item>();
		list.addListSelectionListener(new ListSelectionListener() {
			public void valueChanged(ListSelectionEvent arg0) {
				if (arg0.getValueIsAdjusting() == false) {
					if (list.getSelectedIndex() != -1) {
						Item selectedItem = (Item) list.getSelectedValue();
						for (int i = 0; i < dictionary.size(); i++)
							if (dictionary.get(i).getTu()
									.equalsIgnoreCase(selectedItem.getTu())) {
								lbTu.setText("Từ: " + dictionary.get(i).getTu());
								lbNghia.setText(dictionary.get(i).getNghia());
								break;
							}
					}
				}
			}
		});
		list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		JScrollPane pane = new JScrollPane(list);
		panel.add(pane, BorderLayout.CENTER);

		//loadDictionary();

		lbTu = new JLabel("T\u1EEB:");
		lbTu.setFont(new Font("Tahoma", Font.PLAIN, 12));
		lbTu.setForeground(Color.BLACK);
		lbTu.setBackground(Color.PINK);
		lbTu.setBounds(269, 11, 289, 14);
		contentPane.add(lbTu);

		lbN = new JLabel("Ngh\u0129a:");
		lbN.setBounds(269, 59, 289, 26);
		contentPane.add(lbN);

		lbNghia = new JTextPane();
		lbNghia.setEditable(false);
		lbNghia.setBounds(269, 96, 302, 245);
		contentPane.add(lbNghia);

		txtTu = new JTextField();
		txtTu.setBounds(10, 9, 140, 20);
		contentPane.add(txtTu);
		txtTu.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {

			}
		});
		txtTu.setColumns(10);
		JButton btnNewButton = new JButton("Tra c\u1EE9u");
		btnNewButton.setBounds(190, 8, 69, 23);
		contentPane.add(btnNewButton);
		btnNewButton.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				for (int i = 0; i < dictionary.size(); i++)
					if (dictionary.get(i).getTu()
							.equalsIgnoreCase(txtTu.getText())) {
						lbTu.setText("Từ: " + dictionary.get(i).getTu());
						lbNghia.setText(dictionary.get(i).getNghia());
						return;
					}
				lbTu.setText("Từ: Không tìm thấy");
				lbNghia.setText("Không tìm thấy");
			}
		});
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation(dim.width / 2 - this.getSize().width / 2, dim.height / 2
				- this.getSize().height / 2);
	}

	private void loadDictionary() {
		DefaultListModel listModel = new DefaultListModel();
		for (int i = 0; i < dictionary.size(); i++) {
			listModel.addElement(dictionary.get(i));
		}
		list.setModel(listModel);
	}

	private void createDictionary() {
		dictionary = new ArrayList<Item>();
		dictionary.add(new Item("A", "Một"));
		dictionary.add(new Item("An", "Một"));
		dictionary.add(new Item("Zero", "Không"));
		dictionary.add(new Item("Hello", "Xin chào"));
		dictionary.add(new Item("Good bye", "Tạm biệt"));
		dictionary.add(new Item("Sorry", "Xin lỗi"));

		Collections.sort(dictionary, new Comparator<Item>() {

			@Override
			public int compare(Item o1, Item o2) {
				// TODO Auto-generated method stub
				return o1.getTu().compareTo(o2.getTu());
			}
		});
	}
}

class ItemRender extends JLabel implements ListCellRenderer<Item> {

	@Override
	public Component getListCellRendererComponent(JList<? extends Item> list,
			Item value, int index, boolean isSelected, boolean cellHasFocus) {

		String code = value.getTu();
		ImageIcon imageIcon = new ImageIcon(getClass().getResource(
				"/images/icon.png"));

		setIcon(imageIcon);
		setText(value.getTu());
		if (isSelected) {
			setBackground(Color.BLACK);
			setForeground(Color.BLUE);
			setFont(new Font("Tahoma", Font.PLAIN, 15));
		} else {
			setBackground(list.getBackground());
			setForeground(list.getForeground());
		}
		return this;
	}

}
